import { HttpClientService } from './../../httpClient/http';
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'
@Component({
    selector: 'cp-image-upload',
    templateUrl: './img-upload.component.html',
    styleUrls: ['./img-upload.component.scss']
})
export class ImgUploadComponent {

    public uploadFile = [];
    public urlFile = [];

    public isUpdate = false;

    filesImg = [];
    multiple = false;
    multipleTab = 1;

    constructor(private http: HttpClientService) { }

    fileChange(params) {
        const { files, type, index } = params;
        this.isUpdate = true;
        this.filesImg = files.slice(0, 6);
    }

    imageClick(params) {
        console.log(params);
    }

    //上传
    uploadImg(callback,errorback?) {

        // this.upload((res)=>{
        //     console.log(res);

        // });

        this.upload(callback,errorback);
    }

    //api
    upload(callback,errorback?) {

        this.filesImg.forEach((element, index) => {

            const formData = new FormData();
            let base64 = element['url'];
            let blob = this.dataURLtoBlob(base64)//base64转 二进制文件
            let imgType = this.formatImgType(base64)

            formData.append('file', blob, this.random_string(20) + imgType);

            this.http.imgUpLoad(formData, '/House1/Upload.ashx?target=FileCommentDirectory&watermark=white', res => {

                this.urlFile.push(res);
                //当图片全部上传完成 执行回调
                if (index === this.filesImg.length-1) {

                    callback(this.urlFile);
                }
            },error=>{
                if(errorback){
                    errorback(error)
                }
            });
        });


    }

    dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], {
            type: mime
        });
    }


    formatImgType(base64) {
        let type = base64.split(',')[0].split('/')[1].split(';')[0];
        if (type === 'jpeg') {
            type = 'jpg'
        }
        return '.' + type;
    }


    random_string(len) {

        len = len || 32;

        let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
        let maxPos = chars.length;
        let pwd = '';

        for (var i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }



}